import type {
  AppRouteRecordRaw,
  ComponentRecordType,
  GenerateMenuAndRoutesOptions,
} from '@vben/types';

import { generateAccessible } from '@vben/access';
import { preferences } from '@vben/preferences';
import { convertServerMenuToRouteRecordStringComponent } from '@vben/utils';

import { getMenuList } from '#/api/system/menu';
import { BasicLayout, IFrameView } from '#/layouts';

const forbiddenComponent = () => import('#/views/_core/fallback/forbidden.vue');

async function generateAccess(options: GenerateMenuAndRoutesOptions) {
  const pageMap: ComponentRecordType = import.meta.glob('../views/**/*.vue');

  const layoutMap: ComponentRecordType = {
    BasicLayout,
    IFrameView,
  };
  return await generateAccessible(preferences.app.accessMode, {
    ...options,
    fetchMenuListAsync: async () => {
      // ElMessage({
      //   duration: 1500,
      //   message: `${$t('common.loadingMenu')}...`,
      // });
      const home = {
        name: 'Workspace',
        path: '/home',
        component: '/dashboard/workspace/index',
        type: 'menu',
        meta: {
          icon: 'carbon:home',
          title: '首页',
          affixTab: true, // 固定标签
          tabClosable: false, // 不可关闭
          hideTitle: true, // 隐藏标题（只显示图标）
          order: -999,
        },
      };
      const accessMenus = await getMenuList();

      const accessMenusAll = [home, ...accessMenus];
      return convertServerMenuToRouteRecordStringComponent(
        accessMenusAll as AppRouteRecordRaw[],
      );
      // 由于 yudao 通过 accessStore 读取，所以不在进行 message.loading 提示
      // 补充说明：accessStore.accessMenus 一开始是 AppRouteRecordRaw 类型（后端加载），后面被赋值成 MenuRecordRaw 类型（前端转换）
      // const accessMenus = accessStore.accessMenus as AppRouteRecordRaw[];
      // console.log(`菜单${accessMenus}`);
      // // const accessMenus = (await getMenuList()) as AppRouteRecordRaw[];
      // return convertServerMenuToRouteRecordStringComponent(accessMenus);
    },
    // 可以指定没有权限跳转403页面
    forbiddenComponent,
    // 如果 route.meta.menuVisibleWithForbidden = true
    layoutMap,
    pageMap,
  });
}

export { generateAccess };
